package cn.xuyang520.tyim.sys.config;


import cn.xuyang520.tyim.sys.domain.TySysUser;
import cn.xuyang520.tyim.sys.domain.TySysUserRepository;
import cn.xuyang520.tyim.sys.service.TySysAuthorityService;
import cn.xuyang520.tyim.sys.service.TySysUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;


import java.util.ArrayList;
import java.util.List;

/**
 * 自定义授权
 */
public class TySysShiroRealm extends AuthorizingRealm {
    @Autowired
    private TySysUserRepository tySysUserRepository;
    @Autowired
    TySysUserService tySysUserService;
    @Autowired
    TySysAuthorityService tySysAuthorityService;


    //认证.登录
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken utoken = (UsernamePasswordToken) token;//获取用户输入的token
        String username = utoken.getUsername();
        TySysUser tbUsername = tySysUserRepository.findByTbUsername(username);

        if (tbUsername == null)
            return null;
        return new SimpleAuthenticationInfo(tbUsername, tbUsername.getTbPassword(), this.getClass().getName());
    }
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
        TySysUser user = (TySysUser) principal.fromRealm(this.getClass().getName()).iterator().next();//获取session中的用户
        List<String> permissions = new ArrayList<>();

        List<String> tbGroupIdByTbId = tySysUserService.findGroupIdsByCode(user.getTbId());

        for (String tbGroupId: tbGroupIdByTbId) {
            permissions.addAll(tySysAuthorityService.findAuthorityCodesByGroupCode(tbGroupId));
        }

        System.out.println("校验权限:用户" + user.getTbName() + "拥有权限:" + permissions);


        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //info.addRole("admin");

        info.addStringPermissions(permissions);//将权限放入shiro中.
        return info;
    }

}
